package cn.tedu.sp11.fallback;


import cn.tedu.web.util.JsonResult;
import org.springframework.cloud.netflix.zuul.filters.route.FallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Component
public class ItemFb implements FallbackProvider {
//getroute 返回一个serviceid 针对指定的服务进行降级处理
    // 返回* 或null 值 表示对所有的服务都应用这个降级类

    @Override
    public String getRoute() {
        return "item-service";
    }


    //降级响应 返回一个封装响应数据的response 对象

    @Override
    public ClientHttpResponse fallbackResponse(String route, Throwable cause) {
        return new ClientHttpResponse() {
            @Override
            //返回200 "ok"
            public HttpStatus getStatusCode() throws IOException {
                return HttpStatus.OK;
            }

            @Override
            //返回200
            public int getRawStatusCode() throws IOException {
                return HttpStatus.OK.value();
            }

            @Override
            //返回"ok"
            public String getStatusText() throws IOException {
                return HttpStatus.OK.getReasonPhrase();
            }

            @Override
            public void close() {

            }

            @Override
            public InputStream getBody() throws IOException {
                String json= JsonResult.err().msg("调用商品服务失败").toString();
                return new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
            }

            @Override
            public HttpHeaders getHeaders() {

                HttpHeaders h = new HttpHeaders();
                h.add("Content-Type","application/json;charset=UTF-8");
                return h;


            }

        };
    }
}
